<template>
  <div class="q-pa-sm">
    <create-role ref="addRole" @create="create" />
    <set-authority ref="authority" @update="update" />
    <q-table
      :rows="roleList"
      :columns="columns"
      row-key="name"
      class="full-height q-mr-sm"
      :title="$t(lang + 'text1')"
    >
      <template v-slot:top-right>
        <q-btn
          no-caps
          icon="add"
          outline
          color="primary"
          :label="$t(lang + 'text2')"
          @click="addRole.show()"
        />
      </template>
      <template v-slot:body-cell-operate="props">
        <q-td class="text-center q-gutter-x-sm">
          <q-btn
            no-caps
            outline
            color="secondary"
            :label="$t(lang + 'text3')"
            @click="authority.show(props.row)"
          />
          <q-btn
            outline
            color="red"
            :label="$t('del')"
            @click="remove(props.row)"
          />
        </q-td>
      </template>
    </q-table>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useQuasar } from "quasar";
import CreateRole from "components/user/CreateRole.vue";
import SetAuthority from "components/user/SetAuthority.vue";
import { useUiStore } from "stores/ui";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const lang = "userIndex.RoleManage.";
const $q = useQuasar();
const ui = useUiStore();
const addRole = ref();
const authority = ref();
const columns = [
  {
    name: "roleName",
    align: "center",
    label: t(lang + "text4"),
    field: "roleName",
  },
  {
    name: "operate",
    align: "center",
    label: t(lang + "text5"),
    field: "operate",
  },
];
const roleList = ref([
  { id: "1", roleName: t(lang + "text6"), info: "" },
  { id: "2", roleName: t(lang + "text7"), info: "" },
  { id: "3", roleName: t(lang + "text8"), info: "" },
]);

// 删除角色
function remove(data) {
  $q.dialog({
    title: t("del") + '"' + data.roleName + '"' + t(lang + "text4"),
    message: t(lang + "text9"),
    cancel: t("cancel"),
    ok: t("ok"),
    dark: ui.isDark,
    persistent: true,
  }).onOk(() => {
    roleList.value.forEach((item, index) => {
      if (item.id === data.id) {
        roleList.value.splice(index, 1);
      }
    });
    $q.notify({ type: "positive", message: t(lang + "text10") });
  });
}
// 创建角色
function create(role) {
  role.id = roleList.value.length + 1;
  roleList.value.push(role);
  $q.notify({ type: "positive", message: t(lang + "text11") });
}
// 修改权限
function update(role) {
  roleList.value.forEach((item, index) => {
    if (item.id === role.id) {
      roleList.value[index].info = role.info;
    }
  });
  $q.notify({ type: "positive", message: t(lang + "text12") });
}
</script>

<style scoped></style>
